/*
 * Copyright 2002-2016 the atnoce.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.utils;

import org.apache.commons.lang.StringUtils;

import java.sql.*;

/**
 * @author atnoce.com
 * @date 2016/11/4
 * @since 1.0.0
 */
public class DbUtils {
    private static Connection conn=null;
    private static Statement stat=null;
    private static DatabaseMetaData metaData=null;

    /**
     * 根据配置信息打开数据库链接，可以使用默认的数据库，也可以自定义数据库位置
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    private static void openConn() throws ClassNotFoundException, SQLException {
        if (conn==null){
            Class.forName("org.sqlite.JDBC");
            if(StringUtils.isBlank(Cache.getProConfig(Const.DB_PATH))){
                conn= DriverManager.getConnection("jdbc:sqlite:onepass.db");
            }else{
                String dbpath = Cache.getProConfig(Const.DB_PATH);
                conn=DriverManager.getConnection("jdbc:sqlite://"+dbpath.replace("\\", "/")+"/onepass.db");
            }
        }
        if(stat==null){
            stat=conn.createStatement();
        }
        if(metaData==null){
            metaData=conn.getMetaData();
        }
    }

    /**
     * 关闭数据库连接
     * @throws SQLException
     */
    public static void close() throws SQLException{
        if(conn!=null){

            conn.close();
            conn=null;
        }
    }

    /**
     * 初始化数据库
     *
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static void initTables(boolean initAdmin) throws ClassNotFoundException, SQLException{
        openConn();
        ResultSet table=null;
        table = metaData.getTables(null, null, "passitem", null);
        if(!table.next()){
            stat.executeUpdate("create table passitem (passId text, account text,passwordStr char(500),remarkStr char(500),"
                    + "createTime char(50),modifyTime char(50),isDelete char(8),dirTypeId char(50),sync char(8));");
        }
        table = metaData.getTables(null, null, "fenlei", null);
        if(!table.next()){
            stat.executeUpdate("create table fenlei (dirId char(50), dirName char(50),createTime char(50),modifyTime char(50),sync char(8),isDelete char(8));");
        }
        table = metaData.getTables(null, null, "onepassconfig", null);
        if(!table.next()){
            stat.executeUpdate("CREATE TABLE onepassconfig (xiaoXieStrQuanZhong  char(10),strQuanZhong  char(2)," +
                    "numQuanZhong  char(2),fuhaoQuanZhong  char(2),mainPass  char(512),filterStr  char(10)," +
                    "passLength char(10),startAutoUpdate  char(10),minSysTuoPan  char(10),closeMinWindowNoClose  char(10)," +
                    "autoClearPanel char(10),autoClearPanelTime  char(10),minningLock  char(10),kongXianLock  char(10)," +
                    "kongXianLockTime  char(10),coludAccount char(256),sync char(8),modifyTime char(50));");
            //初始化默认密码为123
            if (initAdmin)
            stat.execute("insert into onepassconfig values ('3','1','1','2'," +
                    "'b544249b186a48b42693b00e0eea358d9e62089579ebb7e29de01afb62f0f0a0ccfa4de3cd217ddf0d1af51f8ed48e3081c667770f91d3d82011a5efb44d6b70'," +
                    "'true','8','false','true','true','true','30','true','true','1200',NULL,'false','1000');");
        }
    }

    /**
     * 获取数据库连接
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public static Connection getDBConnection() throws ClassNotFoundException, SQLException{
        if(conn==null){
            openConn();
        }
        return conn;
    }
}
